package cn.vic.genertor.view;

import cn.vic.config.Configuration;
import cn.vic.config.GenertorConfig;
import cn.vic.config.HistoricalRecord;
import cn.vic.config.TypeMapping;
import cn.vic.config.model.DatabaseElement;
import cn.vic.db.Database;
import cn.vic.db.DatabaseFactory;
import cn.vic.db.model.Table;
import cn.vic.genertor.engine.FreeMarkrTemplate;
import cn.vic.genertor.engine.GenerateInterface;
import cn.vic.genertor.view.ui.TreeNodeData;
import cn.vic.model.RepidModel;
import cn.vic.util.FileUtil;
import cn.vic.util.StringUtil;
import cn.vic.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.*;
import java.util.concurrent.*;

public class LoadAotuCodeViewHistory extends javax.swing.JDialog {
    /**
     * 线程池
     */
    private ExecutorService NEW_FIXED_THREAD_POOL;
    /**
     *
     */
    private CompletionService<Table> completionService;
    /**
     * 多个表集合
     */
    private java.util.List<Table> tableModels = new ArrayList<>();
    /**
     * 配置信息
     */
    private Configuration configuration;
    /**
     * 表名
     */
    private String tableNames;
    /**
     * 选中的tree列表
     */
    private TreePath[] selectionPaths;
    /**
     * sql 对应 java 的配置信息
     */
    private TypeMapping typeMapping;

    /**
     * 生成
     * new {@link FreeMarkrTemplate}
     */
    private GenerateInterface generate = new FreeMarkrTemplate();
    /**
     * 历史记录
     */
    private HistoricalRecord historicalRecord = new HistoricalRecord();


    /**
     * Creates new form NewJDialog
     */
    public LoadAotuCodeViewHistory(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public LoadAotuCodeViewHistory(Frame parent, Configuration configuration, String tableNames) {
        super(parent, true);
        init(parent, configuration, tableNames);
    }

    public LoadAotuCodeViewHistory(Frame parent, Configuration configuration, Table... tableModels) {
        super(parent, true);
        this.tableModels.addAll(Arrays.asList(tableModels));
        StringBuffer tableName = new StringBuffer();
        for (Table tableModel : tableModels) {
            tableName.append(tableModel.getTableName()).append(";");
        }
        init(parent, configuration, tableName.toString());
    }

    /**
     * 初始�? 方法
     *
     * @param parent
     * @param configuration
     * @param tableNames
     */
    private void init(Frame parent, Configuration configuration, String tableNames) {
        //初始化view 配置
        initComponents();
        setTitle("生成配置");
        setResizable(false);
        setIconImage(parent.getIconImage());

        ButtonGroup group = new ButtonGroup();
        group.add(coverRadioButtonYes);
        group.add(coverRadioButtonNo);
        coverRadioButtonNo.setSelected(true);

        outputProgressBar.setStringPainted(true);
//        int x = parent.getX() + parent.getWidth() / 2 - this.getWidth() / 2;
//        int y = parent.getY() + parent.getHeight() / 2 - this.getHeight() / 2;
//        this.setBounds(x, y, 700, 453);
        this.setLocation(parent.getX() + parent.getWidth() / 2 - this.getWidth() / 2,
                parent.getY() + parent.getHeight() / 2 - this.getHeight() / 2);

        historicalRecord.loadGenertorConfig();
        this.configuration = configuration;
        this.tableNames = tableNames;
        NEW_FIXED_THREAD_POOL = Executors.newFixedThreadPool(Integer.valueOf(configuration.getOutThreadNum()));
        completionService = new ExecutorCompletionService<>(NEW_FIXED_THREAD_POOL);
        textHandle();
        //设置 config 历史数据
        List<GenertorConfig> genertorConfigList = historicalRecord.getList();
        GenertorConfig[] genertorConfigs = new GenertorConfig[genertorConfigList.size()];
        //倒序
        Collections.sort(genertorConfigList, new Comparator<GenertorConfig>() {
            @Override
            public int compare(GenertorConfig o1, GenertorConfig o2) {
                if (o1.getCreateTime().getTime() > o2.getCreateTime().getTime()) {
                    return -1;
                }
                if (o1.getCreateTime().getTime() < o2.getCreateTime().getTime()) {
                    return 1;
                }
                return 0;
            }
        });
        genertorConfigList.toArray(genertorConfigs);
        historyList.setListData(genertorConfigs);
        historyList.setSelectedIndex(0);
    }

    /**
     * 给文本进行赋值
     */
    private void textHandle() {
        //表名
        tableField.setText(tableNames);
        tableField.setEnabled(false);

        GenertorConfig genertorConfig = historicalRecord.getNewestConfig();
        if (genertorConfig != null) {
            moduleField.setText(genertorConfig.getModular());
            customParamArea.setText(genertorConfig.getCustomParam());

            basePackageField.setText(genertorConfig.getBasePackage());
            templatePathField.setText(genertorConfig.getTemplatePath());
            outputPathField.setText(genertorConfig.getOutputPath());
        }
        //设置绝对高度 宽度
        Dimension dimension = tableField.getSize();
        dimension.setSize(dimension.getWidth(), dimension.getHeight());
        tableField.setPreferredSize(dimension);

        dimension = basePackageField.getSize();
        dimension.setSize(dimension.getWidth(), dimension.getHeight());
        basePackageField.setPreferredSize(dimension);

        dimension = moduleField.getSize();
        dimension.setSize(dimension.getWidth(), dimension.getHeight());
        moduleField.setPreferredSize(dimension);

//        dimension = customParamArea.getSize();
//        dimension.setSize(dimension.getWidth(), dimension.getHeight());
//        customParamArea.setPreferredSize(dimension);

        dimension = templatePathField.getSize();
        dimension.setSize(dimension.getWidth(), dimension.getHeight());
        templatePathField.setPreferredSize(dimension);

        dimension = outputPathField.getSize();
        dimension.setSize(dimension.getWidth(), dimension.getHeight());
        outputPathField.setPreferredSize(dimension);
    }

    /**
     * 显示文件
     *
     * @param jTextField
     */
    private void showFilePanle(JTextField jTextField) {
        JFileChooser jFileChooser1 = new JFileChooser();
        //设置打开路径
        String path = FileUtil.getFilePathByRun(jTextField.getText());
        jFileChooser1.setCurrentDirectory(new File(path));
        jFileChooser1.setMultiSelectionEnabled(false);
        jFileChooser1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        int result = jFileChooser1.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser1.getSelectedFile();
            String filepath = file.getAbsolutePath();
            // 将文件路径设到JTextField
            jTextField.setText(FileUtil.getFilePathBySave(filepath));
        }
    }

    /**
     * 设置页面
     *
     * @param config
     */
    private void setViewParam(GenertorConfig config) {
        basePackageField.setText(config.getBasePackage());
        moduleField.setText(config.getModular());
        customParamArea.setText(config.getCustomParam());
        templatePathField.setText(config.getTemplatePath());
        outputPathField.setText(config.getOutputPath());
        if (config.isCover()) {
            coverRadioButtonYes.setSelected(true);
        } else {
            coverRadioButtonNo.setSelected(true);
        }
    }

    /**
     * 获取页面参数
     *
     * @return
     */
    private GenertorConfig getViewParam() {
        GenertorConfig genertorConfig = new GenertorConfig();
        genertorConfig.setBasePackage(basePackageField.getText());
        genertorConfig.setModular(moduleField.getText());
        genertorConfig.setCustomParam(customParamArea.getText());
        genertorConfig.setTemplatePath(templatePathField.getText());
        genertorConfig.setOutputPath(outputPathField.getText());
        genertorConfig.setCover(coverRadioButtonYes.isSelected() ? true : false);

        if (StringUtil.isEmpty(genertorConfig.getBasePackage())) {
            JOptionPane.showMessageDialog(this, "请输入包名.", "提示", JOptionPane.INFORMATION_MESSAGE);
            return null;
        }
        if (StringUtil.isEmpty(genertorConfig.getTemplatePath())) {
            JOptionPane.showMessageDialog(this, "请选择 模版路径.", "提示", JOptionPane.INFORMATION_MESSAGE);
            return null;
        }
        if (StringUtil.isEmpty(genertorConfig.getOutputPath())) {
            JOptionPane.showMessageDialog(this, "请选择 保存路径", "提示", JOptionPane.INFORMATION_MESSAGE);
            return null;
        }
        if (StringUtils.isNotBlank(genertorConfig.getCustomParam())) {
            try {
                JSONObject object = JSONObject.parseObject(genertorConfig.getCustomParam());
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, e.getMessage(), "提示", JOptionPane.INFORMATION_MESSAGE);
                return null;
            }
        }
        genertorConfig.setCreateTime(new Date());
        return genertorConfig;
    }

    /**
     * 异步调用生成方法
     * 并且关闭窗口
     */
    private void genertorAlsoCloseView() {

        GenertorConfig genertorConfig = getViewParam();
        if (genertorConfig == null) {
            return;
        }
        historicalRecord.addRecord(genertorConfig);
        historicalRecord.save();
        //判断是否多条数据
        if (selectionPaths != null && selectionPaths.length > 0) {
            //使用多线程获取表信息
            threadGetTableGenertor(genertorConfig);
        } else {
            //有table对象信息
            singleTableGenertor(genertorConfig);
        }
        //200毫秒关闭窗口
        java.util.Timer timers = new java.util.Timer();
        timers.schedule(new TimerTask() {
            @Override
            public void run() {
                doClose();
            }
        }, 200);

    }

    /**
     * 单个 处理
     * 不使用线程处理
     */
    private void singleTableGenertor(GenertorConfig config) {

        outputProgressBar.setValue(10);
        RepidModel model = new RepidModel();
        model.setTableName("");
        model.setPackages(config.getBasePackage());
        model.setModule(config.getModular());
        model.addCustomParam(config.getCustomParam());
        model.setTemplatePath(FileUtil.getFilePathByRun(config.getTemplatePath()));
        model.setSavePath(FileUtil.getFilePathByRun(config.getOutputPath()));
        model.setCover(config.isCover());
        model.setTableModels(tableModels);
        outputProgressBar.setValue(30);
        outputProgressBar.setValue(50);
        outputProgressBar.setValue(70);

        generate.setHasOpen(true);
        generate.processToFile(model);
        outputProgressBar.setValue(100);
        outputProgressBar.setString("处理完成");
    }

    /**
     * 多线程处理 获取表信息
     */
    public void threadGetTableGenertor(GenertorConfig config) {
        if (selectionPaths == null || selectionPaths.length == 0 || typeMapping == null) {
            return;
        }

        for (TreePath treePath : selectionPaths) {
            completionService.submit(new LoadAotuCodeViewHistory.GetLoaderTable(treePath, typeMapping));
        }
        int count = selectionPaths.length;
        //jProgressBar自带调整显示百分比
        //jProgressBar.setMaximum(count);
        for (int i = 0; i < count; i++) {
            try {
                Future<Table> future = completionService.take();
                Table table = future.get();

                RepidModel model = new RepidModel();
                model.setTableName("");
                model.setPackages(config.getBasePackage());
                model.setModule(config.getModular());
                model.addCustomParam(config.getCustomParam());
                model.setTemplatePath(FileUtil.getFilePathByRun(config.getTemplatePath()));
                model.setSavePath(FileUtil.getFilePathByRun(config.getOutputPath()));
                model.setCover(config.isCover());
                model.setTableModels(table);

                if (i + 1 == count) {
                    generate.setHasOpen(true);
                }
                generate.processToFile(model);


                double num = 100d / count * (i + 1);
                System.err.println(num + " >>> " + new Double(Math.floor(num)).intValue());
                outputProgressBar.setValue(new Double(Math.floor(num)).intValue());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        outputProgressBar.setString("处理完成");
    }


    /**
     * 线程获取table对象
     */
    private class GetLoaderTable implements Callable<Table> {

        private TreePath treePath;
        private TypeMapping typeMapping;

        GetLoaderTable(TreePath treePath, TypeMapping typeMapping) {
            this.treePath = treePath;
            this.typeMapping = typeMapping;
        }

        @Override
        public Table call() throws SQLException {
            Connection connection = null;
            try {
                DefaultMutableTreeNode mutableTreeNode = (DefaultMutableTreeNode) treePath.getLastPathComponent();
                TreeNodeData treeNodeData1 = (TreeNodeData) mutableTreeNode.getUserObject();
                DatabaseElement databaseElement = treeNodeData1.getDatabaseElement();
                connection = databaseElement.getConnection(treeNodeData1.getDataBase());
                Database db = DatabaseFactory.createDatabase(connection, typeMapping);
                String nodeText = treeNodeData1.getText();
                String tableSchema = null;
                String tableName = nodeText;
                if (nodeText.indexOf(".") > 0) {
                    tableName = nodeText.substring(nodeText.indexOf(".") + 1);
                    tableSchema = nodeText.substring(0, nodeText.indexOf("."));
                }
                Table table = db.getTable(null, tableSchema, tableName);
                return table;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.isReadOnly();
                }
            }
            return null;
        }
    }

    private void doClose() {
        setVisible(false);
        dispose();
    }

    public void setSelectionPaths(TreePath[] selectionPaths) {
        this.selectionPaths = selectionPaths;
    }

    public void setTypeMapping(TypeMapping typeMapping) {
        this.typeMapping = typeMapping;
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        basePackageField = new javax.swing.JTextField();
        tableLabel = new javax.swing.JLabel();
        moduleField = new javax.swing.JTextField();
        basePackageLabel = new javax.swing.JLabel();
        templatePathField = new javax.swing.JTextField();
        moduleLabel = new javax.swing.JLabel();
        outputPathField = new javax.swing.JTextField();
        customParamLabel1 = new javax.swing.JLabel();
        templateButton = new javax.swing.JButton();
        templateLabel = new javax.swing.JLabel();
        outputButton = new javax.swing.JButton();
        outputLabel = new javax.swing.JLabel();
        tableField = new javax.swing.JTextField();
        customParamLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        customParamArea = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        historyList = new javax.swing.JList<>();
        jPanel1 = new javax.swing.JPanel();
        coverRadioButtonNo = new javax.swing.JRadioButton();
        coverRadioButtonYes = new javax.swing.JRadioButton();
        coverLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        outputProgressBar = new javax.swing.JProgressBar();
        cancelButton = new javax.swing.JButton();
        generateButton = new javax.swing.JButton();

        tableLabel.setText("表名");

        basePackageLabel.setText("basePackage");

        moduleLabel.setText("module");

        outputPathField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                outputPathFieldActionPerformed(evt);
            }
        });

        customParamLabel1.setText("自定义参数");

        templateButton.setText("浏览");
        templateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                templateButtonActionPerformed(evt);
            }
        });

        templateLabel.setText("模板路径");

        outputButton.setText("浏览");
        outputButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                outputButtonActionPerformed(evt);
            }
        });

        outputLabel.setText("输出路径");

        tableField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tableFieldActionPerformed(evt);
            }
        });

        customParamLabel2.setText("(JSON)");

        customParamArea.setColumns(20);
        customParamArea.setRows(5);
        customParamArea.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                customParamAreaFocusGained(evt);
            }

            public void focusLost(java.awt.event.FocusEvent evt) {
                customParamAreaFocusLost(evt);
            }
        });
        jScrollPane2.setViewportView(customParamArea);

        historyList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                historyListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(historyList);

        coverRadioButtonNo.setText("否");
        coverRadioButtonNo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                coverRadioButtonNoActionPerformed(evt);
            }
        });

        coverRadioButtonYes.setText("是");
        coverRadioButtonYes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                coverRadioButtonYesActionPerformed(evt);
            }
        });

        coverLabel.setText("覆盖输出");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addContainerGap(23, Short.MAX_VALUE)
                                .addComponent(coverLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(coverRadioButtonYes)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(coverRadioButtonNo)
                                .addGap(21, 21, 21))
        );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(coverRadioButtonNo)
                                .addComponent(coverRadioButtonYes)
                                .addComponent(coverLabel))
        );

        cancelButton.setText("取消");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        generateButton.setText("生成");
        generateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generateButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(outputProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 532, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cancelButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(generateButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(outputProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(cancelButton)
                                .addComponent(generateButton))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addGroup(layout.createSequentialGroup()
                                                                .addGap(14, 14, 14)
                                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                                                .addComponent(basePackageLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                                                                                                .addComponent(tableLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                                                                                                .addComponent(moduleLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                                                                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                                                .addComponent(customParamLabel2)
                                                                                                .addComponent(customParamLabel1)))
                                                                                .addComponent(outputLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                                                                        .addComponent(templateLabel))
                                                                .addGap(13, 13, 13)
                                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                                                .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                                                                                .addComponent(moduleField, javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addComponent(basePackageField, javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addComponent(tableField, javax.swing.GroupLayout.Alignment.LEADING))
                                                                        .addGroup(layout.createSequentialGroup()
                                                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                                                        .addComponent(outputPathField, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                                                                                        .addComponent(templatePathField))
                                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                                        .addComponent(templateButton)
                                                                                        .addComponent(outputButton)))))
                                                        .addGroup(layout.createSequentialGroup()
                                                                .addGap(18, 18, 18)
                                                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(tableLabel)
                                                        .addComponent(tableField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(basePackageLabel)
                                                        .addComponent(basePackageField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(moduleLabel)
                                                        .addComponent(moduleField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addGroup(layout.createSequentialGroup()
                                                                .addGap(25, 25, 25)
                                                                .addComponent(customParamLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(customParamLabel2)))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(templatePathField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(templateButton)
                                                        .addComponent(templateLabel))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(outputButton)
                                                        .addComponent(outputPathField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(outputLabel))
                                                .addGap(13, 13, 13)
                                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(13, 13, 13)
                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void outputPathFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_outputPathFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_outputPathFieldActionPerformed

    private void templateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_templateButtonActionPerformed
        // TODO add your handling code here:
        showFilePanle(templatePathField);
    }//GEN-LAST:event_templateButtonActionPerformed

    private void coverRadioButtonYesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_coverRadioButtonYesActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_coverRadioButtonYesActionPerformed

    private void coverRadioButtonNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_coverRadioButtonNoActionPerformed
        // TODO add your handling code here:
        //
    }//GEN-LAST:event_coverRadioButtonNoActionPerformed

    private void outputButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_outputButtonActionPerformed
        // TODO add your handling code here:
        showFilePanle(outputPathField);
    }//GEN-LAST:event_outputButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        // TODO add your handling code here:
        doClose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void generateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateButtonActionPerformed
        // TODO add your handling code here:
        GenertorConfig genertorConfig = getViewParam();
        if (genertorConfig == null) {
            return;
        }
        /**
         * 生成处理方法
         * 处理数据
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                genertorAlsoCloseView();
            }
        }).start();
    }//GEN-LAST:event_generateButtonActionPerformed

    private void tableFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tableFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tableFieldActionPerformed

    private void historyListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_historyListValueChanged
        // TODO add your handling code here:
        //变更
        GenertorConfig config = historyList.getSelectedValue();
        if (config != null) {
            setViewParam(config);
        }
    }//GEN-LAST:event_historyListValueChanged

    private void customParamAreaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_customParamAreaFocusGained
        // TODO add your handling code here:
    }//GEN-LAST:event_customParamAreaFocusGained

    private void customParamAreaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_customParamAreaFocusLost
        // TODO add your handling code here:
        //验证JSON是否正确
        JTextArea textArea = (JTextArea) evt.getComponent();
        if (StringUtils.isNotBlank(textArea.getText())) {
            try {
//                JSONObject object = JSONObject.parseObject(textArea.getText());
//                String pretty = JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
//                        SerializerFeature.WriteDateUseDateFormat);
                JsonParser jsonParser = new JsonParser();
                JsonObject jsonObject = jsonParser.parse(textArea.getText()).getAsJsonObject();
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                textArea.setText(gson.toJson(jsonObject));
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, e.getMessage(), "提示", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }//GEN-LAST:event_customParamAreaFocusLost

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoadAotuCodeViewHistory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoadAotuCodeViewHistory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoadAotuCodeViewHistory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoadAotuCodeViewHistory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                LoadAotuCodeViewHistory dialog = new LoadAotuCodeViewHistory(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField basePackageField;
    private javax.swing.JLabel basePackageLabel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel coverLabel;
    private javax.swing.JRadioButton coverRadioButtonNo;
    private javax.swing.JRadioButton coverRadioButtonYes;
    private javax.swing.JTextArea customParamArea;
    private javax.swing.JLabel customParamLabel1;
    private javax.swing.JLabel customParamLabel2;
    private javax.swing.JButton generateButton;
    private javax.swing.JList<GenertorConfig> historyList;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField moduleField;
    private javax.swing.JLabel moduleLabel;
    private javax.swing.JButton outputButton;
    private javax.swing.JLabel outputLabel;
    private javax.swing.JTextField outputPathField;
    private javax.swing.JProgressBar outputProgressBar;
    private javax.swing.JTextField tableField;
    private javax.swing.JLabel tableLabel;
    private javax.swing.JButton templateButton;
    private javax.swing.JLabel templateLabel;
    private javax.swing.JTextField templatePathField;
    // End of variables declaration//GEN-END:variables
}
